﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Zatify.WebUI.Infrastructure;
using System.Web.Security;
using System.Web.Script.Serialization;
using Zatify.WebUI.Infrastructure.Concrete;
using Zatify.WebUI.Infrastructure.Filters;
using System.Configuration;
using Zatify.WebUI.Controllers;

namespace Zatify.WebUI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());

            // COMMENT THESE LINES, TO ALLOW ANONYMOUS ACCESS TO WEBSITE
            //filters.Add(new ZatifyAnonimousAccessRestrictFilter());
            var allowAnonymousAccessToWebSite = Boolean.Parse(ConfigurationManager.AppSettings["AllowAnonymousAccess"]);

            if (!allowAnonymousAccessToWebSite)
                filters.Add(new ZatifyAnonimousAccessRestrictFilter());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //routes.MapRoute(
            //    "Admin_Default", // Route name
            //    "Admin/{action}/{id}", // URL with parameters
            //    new { controller = "Account", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
            //    new string[] { "Zatify.WebUI.Areas.Admin.Controllers" }
            //);

            routes.MapRoute(
                "User_Profile_Categories", // Route name
                "UserProfile/Categories/{categoryId}", // URL with parameters
                new { controller = "UserProfile", action = "Categories", categoryId = UrlParameter.Optional }//, // Parameter defaults
                //new string[] { "Zatify.WebUI.Controllers" }
            );

            routes.MapRoute(
                "Home_Routes", // Route name
                "{action}", // URL with parameters
                new { controller = "Home", action = "Index" } // Parameter defaults
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}", // URL with parameters
                new { controller = "Home", action = "Index" }, // Parameter defaults
                new string[] { "Zatify.WebUI.Controllers" }
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            DependencyResolver.SetResolver(new NinjectDependencyResolver());
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext = ((MvcApplication)sender).Context;
            var ex = Server.GetLastError();

            if (ex is System.Data.EntityCommandExecutionException)
            {
                var controller = new HomeController(null);
                var routeData = new RouteData();
                var action = "SessionExpired";

                httpContext.ClearError();
                httpContext.Response.Clear();
                routeData.Values["controller"] = "Home";
                routeData.Values["action"] = action;
                ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
            }
        }

        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            
            if (authCookie != null)
            {
                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                var serializeModel = new JavaScriptSerializer().Deserialize<ZatifyPrincipalSerializeModel>(authTicket.UserData);

                //if (serializeModel != null)
                //{
                var newUser = new ZatifyPrincipal(authTicket.Name);
                newUser.SecurityToken = serializeModel.Token;
                newUser.Login = serializeModel.Login;
                newUser.UserRole = serializeModel.UserRole;
                newUser.ZipCode = serializeModel.ZipCode;
                newUser.TimeZoneOffset = serializeModel.TimeZoneOffset;

                HttpContext.Current.User = newUser;
                //}
                //else
                //{
                //    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
                //    {
                //        Expires = DateTime.Now.AddDays(-1) // or any other time in the past
                //    };

                //    Response.Cookies.Set(cookie);
                //}
            }
        }
    }
}